package org.example.loadbalancer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * Application
 *
 * @author zhengchalei
 * @date 2021/09/26
 */
@SpringBootApplication
public class LoadBalancerApplication {
    public static void main(String[] args) {
        SpringApplication.run(LoadBalancerApplication.class, args);
    }

    //    @Bean
//    public WebClient webClient(ReactorLoadBalancerExchangeFilterFunction loadBalancerExchangeFilterFunction) {
//        return WebClient.builder()
//                .filter(loadBalancerExchangeFilterFunction)
//                .build();
//    }

    @Bean
    @LoadBalanced
    WebClient.Builder builder() {
        return WebClient.builder();
    }

    @Bean
    WebClient webClient(WebClient.Builder builder) {
        return builder.build();
    }


    @RestController
    static class Echo {

        @Autowired
        private WebClient webClient;

        @RequestMapping("/")
        public Mono<String> echo(@RequestParam(defaultValue = "loadBalancer-service", required = false) String msg) {
            return this.webClient.get()
                    // 注意大小写
                    .uri(URI.create("http://ECHO/echo?msg=" + msg))
//                    .uri(URI.create("http://localhost:8001/echo?msg=" + msg))
                    .retrieve().bodyToMono(String.class);
        }
    }
}
